﻿using ERP.EquipmentManage;
using ERP.EquipmentManage.Dtos;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.EntityFrameworkCore;
using ERP.EntityFrameworkCore;

namespace ERP.Web.Controllers
{
    public class DvsubjectController : Controller
    {
        private readonly IDvsubjectService _dvsubjectService;
        private readonly ERPDbContext _dbContext;

        public DvsubjectController(IDvsubjectService dvsubjectService, ERPDbContext dbContext)
        {
            _dvsubjectService = dvsubjectService;
            _dbContext = dbContext;
        }

        /// <summary>
        /// 首页视图
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 设备类型设置
        /// </summary>
        /// <returns></returns>

        public IActionResult Show()
        {
            return View();
        }

        /// <summary>
        /// 获取分页列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetPagedList(GetDvsubjectInputDto input)
        {
            var result = await _dvsubjectService.GetPagedListAsync(input);
            return Json(new { code = 0, msg = "success", count = result.TotalCount, data = result.Items });
        }

        /// <summary>
        /// 获取类型列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetSubtypeList()
        {
            var result = await _dvsubjectService.GetSubtypeListAsync();
            return Json(new { code = 0, data = result });
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetById(int id)
        {
            try
            {
                var result = await _dvsubjectService.GetByIdAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Create(CreateDvsubjectDto input)
        {
            try
            {
                var result = await _dvsubjectService.CreateAsync(input);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Update(int id, UpdateDvsubjectDto input)
        {
            try
            {
                var result = await _dvsubjectService.UpdateAsync(id, input);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Delete(int id)
        {
            try
            {
                await _dvsubjectService.DeleteAsync(id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 导出选定的数据
        /// </summary>
        /// <param name="ids">选定的ID列表，以逗号分隔</param>
        /// <returns>CSV文件</returns>
        [HttpGet]
        public async Task<IActionResult> ExportSelected(string ids)
        {
            try
            {
                // 解析ID列表
                var idList = ids.Split(',')
                    .Where(x => !string.IsNullOrWhiteSpace(x))
                    .Select(x => int.Parse(x))
                    .ToList();

                if (idList.Count == 0)
                {
                    return Json(new { success = false, message = "请至少选择一条数据" });
                }

                // 获取选定的数据
                var data = await _dvsubjectService.ExportSelectedAsync(idList);

                // 生成CSV内容
                var csv = new StringBuilder();
                
                // 添加标题行
                csv.AppendLine("ID,项目编码,项目名称,项目类型,是否启用,项目内容,标准");
                
                // 添加数据行
                foreach (var item in data)
                {
                    csv.AppendLine($"{item.Id},{item.Subcode},{item.Subname},{item.Subtype},{item.Isdel},{item.Subcontext},{item.Subarea}");
                }

                // 转换为字节数组
                var bytes = Encoding.UTF8.GetBytes(csv.ToString());
                
                // 返回文件
                return File(bytes, "text/csv", $"设备点检保养项目_{DateTime.Now:yyyyMMddHHmmss}.csv");
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
        }






        //=======================================================================================================================================

        /// <summary>
        /// 获取设备类型设置分页列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetDvsubjectList(string subname, int? isdel, int pageIndex = 1, int pageSize = 5)
        {
            // 1. 获取基础查询
            var query = _dbContext.Dvsubject.AsQueryable();

            // 2. 应用筛选条件
            if (!string.IsNullOrWhiteSpace(subname))
            {
                query = query.Where(x => x.Subname.Contains(subname));
            }

            // 修改条件判断逻辑，只有当isdel有值时才进行筛选
            if (isdel.HasValue)
            {
                query = query.Where(x => x.Isdel == isdel.Value);
            }

            // 3. 计算总记录数
            var totalCount = await query.CountAsync();

            // 4. 执行分页查询
            var items = await query
                .OrderByDescending(x => x.Id)
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            // 5. 构建返回结果
            return Json(new
            {
                code = 0,
                msg = "success",
                count = totalCount,
                data = items
            });
        }
    }
}
